//
//  SpiritualGrounding.swift
//  HIextractLicve
//
//  Created by HIextractLicve on 2024/12/12.
//

import UIKit
import ProgressHUD
import AVFoundation


class SpiritualGrounding:UIViewController {
    
    @IBOutlet weak var openCameraHTLCButton: UIButton!
    var mindfulness:Set<Int>?
    var suggestion:Set<String>?
    var  professionals:Set<CGFloat>?
    var exchangeHTLC:[String:Array<Dictionary<String,String>>]?

    var eachVioViewHTLC:THLCNOrBUTTOn?
    var mindfulnessPageHTL:THLCNPageControll?
    var journeyHTLC:UIView?
    
    private var  codeingcamreraSessionHTLC = AVCaptureSession()
    private var posionCamreaHTLC: AVCaptureDevice.Position = .front
    
    
    var layerSongHTLC: AVCaptureVideoPreviewLayer?
    
    var covertLiveing:UIImage
    var themfHTLC:String
    var ifopentenCamrraIsselected:Bool
    
    init(stressdescHTL:Set<Int>,covertLiveing: UIImage, themfHTLC: String,ifopentenCamrraIsselected:Bool) {
        self.covertLiveing = covertLiveing
        self.themfHTLC = themfHTLC
        self.ifopentenCamrraIsselected = ifopentenCamrraIsselected
        super.init(nibName: nil, bundle: nil)
        mindfulness = stressdescHTL
        suggestion = ["decompression"]
        professionals = [12.1]
        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @IBOutlet weak var switchNOwingHTLC: UIButton!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        
       
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
       
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        
        
    }

    var chatDigloglistShowing = HTLROOOMMeasg.init(userDHTL: HTLCAllDealRelaxing.Relaxing.signinUserDataHTL, mesdgtHTLlist: [])
  
    var recorSendGittCount:Int = 1
    var recorGittid:Int = 0
    
    
    lazy var liverdkkChatHTLC: UITableView = {
        var buyijg = UITableView.init(frame: .zero, style: .plain)
        
        buyijg.dataSource = self
        buyijg.delegate = self
        buyijg.backgroundColor = .clear
        buyijg.rowHeight = UITableView.automaticDimension
        buyijg.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom:bommbsafeHeitHTL + 90, right: 0)
        
        
        buyijg.register(ResilienceBuilding.self, forCellReuseIdentifier: "HTLCroomeLiveNormalCellID")
       
            buyijg.estimatedRowHeight = 48
            buyijg.separatorStyle = .none
        
       
        buyijg.allowsSelection = false
        buyijg.showsVerticalScrollIndicator = false
        return buyijg
    }()
    
  
    
     
    
    @IBOutlet weak var liveCVoverHTL: UIImageView!
    

    
    
    
    @IBOutlet weak var userHeaderHTL: UIButton!
    
    @IBOutlet weak var userThemhrHTl: UILabel!
    

    
    @IBOutlet weak var norinfobg0: UIView!
    
    @IBOutlet weak var normalinfobg1: UIView!
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
         
        norinfobg0.layer.cornerRadius = 25
        norinfobg0.layer.maskedCorners = [.layerMaxXMaxYCorner,.layerMaxXMinYCorner]
    }
    
    @IBAction func setingCloseCameraMyLiveTouchHTLC(_ sender: UIButton) {
        
//        let hubai = "Sure****Cancel****Comment".components(separatedBy: "****")
       
        
        if sender.isSelected == false {//开着镜头，去关闭
            let adlkfVC = UIAlertController(title: HTLROOOMMeasg.BinrwetioBase64("Q2xvc2UgdGhlIGNhbWVyYQ=="), message:HTLROOOMMeasg.BinrwetioBase64("QWZ0ZXIgdHVybmluZyBvZmYgdGhlIGNhbWVyYSwgdGhlIGxpdmUgYnJvYWRjYXN0IHJvb20gd2lsbCBiZSB0cmFuc2Zvcm1lZCBpbnRvIGEgdGV4dCBsaXZlIGJyb2FkY2FzdCByb29tIQ==") , preferredStyle: UIAlertController.Style.alert)
            
            adlkfVC.addAction(UIAlertAction(title: HTLROOOMMeasg.BinrwetioBase64("Q29tbWVudA=="), style: .default, handler: { adlet in
                sender.isSelected = true
                self.layerSongHTLC?.isHidden = true
                self.codeingcamreraSessionHTLC.stopRunning()
            }))
            
            adlkfVC.addAction(UIAlertAction(title: HTLROOOMMeasg.BinrwetioBase64("Q2FuY2Vs"), style: .default))
            self.present(adlkfVC, animated: true)
            return
        }
        
        if sender.isSelected == true {//guan着镜头，去打开
            let adlkfVC = UIAlertController(title: HTLROOOMMeasg.BinrwetioBase64("T3BlbiB0aGUgY2FtZXJh"), message:HTLROOOMMeasg.BinrwetioBase64("QWZ0ZXIgdHVybmluZyBvbiB0aGUgY2FtZXJhLCB0aGUgbGl2ZSBicm9hZGNhc3Qgcm9vbSB3aWxsIGRpc3BsYXkgdGhlIGNvbnRlbnQgb2YgdGhlIGNhbWVyYSE=") , preferredStyle: UIAlertController.Style.alert)
            
            adlkfVC.addAction(UIAlertAction(title: HTLROOOMMeasg.BinrwetioBase64("U3VyZQ=="), style: .default, handler: { adlet in
                sender.isSelected = false
                self.layerSongHTLC?.isHidden = false
                DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
                    var huihuo = 43
                    huihuo += 1
                    var pagenorHTLC = 23
                    pagenorHTLC -= 2
                    var community:Set<Int> = [huihuo,pagenorHTLC]
                    if community.first ?? 0 > 2 {
                        self.codeingcamreraSessionHTLC.startRunning()
                    }
                    
                   
                }
            }))
            ifopentenCamrraIsselected = sender.isSelected
            adlkfVC.addAction(UIAlertAction(title: HTLROOOMMeasg.BinrwetioBase64("Q2FuY2Vs"), style: .default))
            self.present(adlkfVC, animated: true)
        }
      
    }
    
 
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        openCameraHTLCButton.isSelected = self.ifopentenCamrraIsselected
        
        
        liveCVoverHTL.layer.masksToBounds = true
        
        normalinfobg1.layer.cornerRadius = 10
        normalinfobg1.layer.masksToBounds = true
        
         
        userHeaderHTL.layer.cornerRadius = 16
        userHeaderHTL.layer.masksToBounds = true
        
        
        liveCVoverHTL.image = covertLiveing
        
        if let headr = HTLCAllDealRelaxing.Relaxing.showingHTLimgHead {
            userHeaderHTL.setImage(headr, for: .normal)
        }
        userThemhrHTl.text = themfHTLC
      
        
        
        let texfieldChatHTL = UITextField.init()
        texfieldChatHTL.returnKeyType = .send
        texfieldChatHTL.delegate = self
        texfieldChatHTL.layer.masksToBounds = true
        texfieldChatHTL.textColor = .white
        texfieldChatHTL.backgroundColor =  UIColor(red: 0, green: 0, blue: 0, alpha:0.6)
        texfieldChatHTL.leftViewMode = .always
        texfieldChatHTL.leftView = UIView(frame: CGRect.init(x: 0, y: 0, width: 25.xHTL, height: 52.xHTL))
        
        texfieldChatHTL.layer.cornerRadius = 24.xHTL
        texfieldChatHTL.attributedPlaceholder = NSAttributedString.init(string: "Say something......", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
        
       
        view.insertSubview(liverdkkChatHTLC, belowSubview: switchNOwingHTLC )
        view.addSubview(texfieldChatHTL)
        
        liverdkkChatHTLC.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            
          
            make.top.equalTo(normalinfobg1.snp.bottom).offset(80.yHTL)
        }
        
        texfieldChatHTL.snp.makeConstraints { make in
            make.leading.equalToSuperview().inset(12)
            make.height.equalTo(48.xHTL)
            make.centerY.equalTo(switchNOwingHTLC)
            make.trailing.equalTo(switchNOwingHTLC.snp.leading).offset(-26.xHTL)
        }
        ProgressHUD.animate()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: DispatchWorkItem(block: {
            var huihuo = 43
            huihuo += 1
            var pagenorHTLC = 23
            pagenorHTLC -= 2
            var community:Set<Int> = [huihuo,pagenorHTLC]
            if community.first ?? 0 > 2 {
                ProgressHUD.succeed(" Create successful!!!")
            }
           
        }))
        
        var huihuo = 43
        huihuo += 1
        var pagenorHTLC = 23
        pagenorHTLC -= 2
        let community:Set<Int> = [huihuo,pagenorHTLC]
        AVAudioSession.sharedInstance().requestRecordPermission { (allowed) in
            
        }
        AVCaptureDevice.requestAccess(for: .video) { granted in
           
        }
        
        guard let cameraHTLC = cahngeCamretPOsitionHTLC(stressdescHTL: community, ocaWeozjoHTLC: posionCamreaHTLC).0,
              let cameraInputHTLC = try? AVCaptureDeviceInput(device: cameraHTLC) else { return }
        
        if codeingcamreraSessionHTLC.canAddInput(cameraInputHTLC) {
            codeingcamreraSessionHTLC.addInput(cameraInputHTLC)
        }
        
        // 设置输出
        let videoOutputHTLC = AVCaptureVideoDataOutput()
        if codeingcamreraSessionHTLC.canAddOutput(videoOutputHTLC) {
            codeingcamreraSessionHTLC.addOutput(videoOutputHTLC)
        }
        
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }

        mindfulnessPageHTL = THLCNPageControll()
        mindfulnessPageHTL?.numberOfPages = 1
        mindfulnessPageHTL?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.tintColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.sizeToFit()

        if journeyHTLC != nil {
            journeyHTLC?.addSubview(mindfulnessPageHTL ?? THLCNPageControll.init())
           
        }

        
        let mylashingLayerHTLC = AVCaptureVideoPreviewLayer(session: codeingcamreraSessionHTLC)
        mylashingLayerHTLC.frame = self.view.frame
        self.layerSongHTLC = mylashingLayerHTLC
         mylashingLayerHTLC.videoGravity = .resizeAspectFill
        self.liveCVoverHTL.layer.insertSublayer(mylashingLayerHTLC, below: self.norinfobg0.layer)
        DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
            var huihuo = 43
            huihuo += 1
            var pagenorHTLC = 23
            pagenorHTLC -= 2
            var community:Set<Int> = [huihuo,pagenorHTLC]
            if community.first ?? 0 > 2 {
                
                if self.ifopentenCamrraIsselected == false {
                    self.codeingcamreraSessionHTLC.startRunning()
                }else{
                    mylashingLayerHTLC.isHidden = true
                }
                
            }
            
           
        }
        switchNOwingHTLC.isUserInteractionEnabled = true
        
        switchNOwingHTLC.addTarget(self, action: #selector(switcameratNowHTL), for: .touchUpInside)
    }
    
    @objc func switcameratNowHTL(_ sender: Any) {
      
            
        codeingcamreraSessionHTLC.beginConfiguration()
      
        if posionCamreaHTLC == .back {
            posionCamreaHTLC = .front
        } else {
            posionCamreaHTLC = .back
        }
        
      
        for input in codeingcamreraSessionHTLC.inputs {
            codeingcamreraSessionHTLC.removeInput(input)
        }
        
        var huihuo = 43
        huihuo += 1
        var pagenorHTLC = 23
        pagenorHTLC -= 2
        let community:Set<Int> = [huihuo,pagenorHTLC]
        guard let camera = cahngeCamretPOsitionHTLC(stressdescHTL: community, ocaWeozjoHTLC:posionCamreaHTLC).0,
            let cameraInput = try? AVCaptureDeviceInput(device: camera) else { return }
        if codeingcamreraSessionHTLC.canAddInput(cameraInput) {
            codeingcamreraSessionHTLC.addInput(cameraInput)
        }
        
        codeingcamreraSessionHTLC.commitConfiguration()
    }
    
    func cahngeCamretPOsitionHTLC(stressdescHTL:Set<Int>,ocaWeozjoHTLC: AVCaptureDevice.Position) -> (AVCaptureDevice?,Int?,Int?) {
       
        let devices = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.builtInWideAngleCamera],
            mediaType: .video,
            position: .unspecified).devices
        
        return (devices.first(where: { $0.position == ocaWeozjoHTLC }),333,555)
       
    }
    
  
    
    @IBAction func Funrightnoweback(_ sender: Any) {
        let hubai = "Sure****Cancel****Comment".components(separatedBy: "****")
       
        
        let adlkfVC = UIAlertController(title: "Exit Live", message: "Confirm to exit the live room you have created. After exiting, the room will be destroyed", preferredStyle: UIAlertController.Style.alert)
        
        adlkfVC.addAction(UIAlertAction(title: HTLROOOMMeasg.BinrwetioBase64("Q29tbWVudA=="), style: .default, handler: { adlet in
            
            self.navigationController?.popToRootViewController(animated: true)
        }))
        
        adlkfVC.addAction(UIAlertAction(title:HTLROOOMMeasg.BinrwetioBase64("Q2FuY2Vs"), style: .default))
        self.present(adlkfVC, animated: true)
    }

    
  
    
}


extension SpiritualGrounding:UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var haoPeold :Set<Int> = [90,790]
        var huanghsi = "decompression****plist".components(separatedBy: "****")
        huanghsi.append("67ye")
        haoPeold.insert(33)
        haoPeold.insert(55)
        if huanghsi.count > 1 {
            haoPeold.insert(65)
        }

        if huanghsi.count > 1 && haoPeold.first ?? 0 > 1 {
            return chatDigloglistShowing.mesgHTLasarry.count
        }
        return chatDigloglistShowing.mesgHTLasarry.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
         let diologData = self.chatDigloglistShowing.mesgHTLasarry[indexPath.row]

        let chateCell = tableView.dequeueReusableCell(withIdentifier: "HTLCroomeLiveNormalCellID", for: indexPath) as! ResilienceBuilding
      
       
      
        chateCell.userHeaderHTL.image = (diologData.0) ? HTLCAllDealRelaxing.Relaxing.showingHTLimgHead :  UIImage(named:  diologData.1["HTLCAvater"] ?? "")
        chateCell.usernamhrHTl.text = (diologData.0) ? "Me" :  (diologData.1["HTLCkiName"] ?? "")
       
        chateCell.saycontentHTl.text =  diologData.2
        
        return chateCell
       
        
    }
    
    
    
    
    //发送正常消息
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        var huanghsi = "decompression****plist****Whoqu".components(separatedBy: "****")
        var huihuo = 43
        huihuo += 1
        var pagenorHTLC = 23
        pagenorHTLC -= 2
        huanghsi.append("WhertogpNowHTL")
        let community:Set<Int> = [huihuo,pagenorHTLC]
       
        textField.resignFirstResponder()
        
            if let conted = textField.text, conted.count != 0 {
                let diologdata = (true,HTLCAllDealRelaxing.Relaxing.signinUserDataHTL,conted,false,0,0)
                
                chatDigloglistShowing.mesgHTLasarry.append(diologdata)
          
                textField.text = nil
                textField.resignFirstResponder()
                
                ProgressHUD.animate()
               
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: DispatchWorkItem(block: {
                    ProgressHUD.dismiss()
                    var haoPeold = community
                    haoPeold.insert(33)
                    haoPeold.insert(55)
                    if huanghsi.count > 1 {
                        haoPeold.insert(65)
                    }
                    if huanghsi.count > 2  && haoPeold.first ?? 0 > 2 {
                        self.liverdkkChatHTLC.reloadData()
                        
                    }
                  
                    
                    
                }))
                
                
                
            }else{
                ProgressHUD.banner("A empty message cannot be send!!!", HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), delay: 2.0)
              
            }
            
            
            
            
            
           
        
        return true
    }
    

}


